#include <iostream>
struct Student{
    char name[10];
    char num[10];
    int score[3];
    float aver;
} stud[5], work;

int main() {
    void sort();
    int i;
    FILE * fp;
    sort();
    fp = fopen("D:\\C\\stud_sort.txt", "rb");
    printf("sorted student's score are as follows\n");
    printf("-----------------------------------------------------------\n");
    printf("NAME NO. SCORE1 SCORE2 SCORE3 AVER \n");
    printf("-----------------------------------------------------------\n");
    for (i = 0; i < 5; i++) {
        fread(&stud[i], sizeof(struct Student), 1, fp);
        printf("%-10s %3d %8d %8d %8d %9.2f\n", stud[i].name, stud[i].num, stud[i].score[0],
               stud[i].score[1], stud[i].score[2], stud[i].aver);
    }
    fclose(fp);
    return 0;
}

void sort() {
    FILE *fp1, *fp2;
    int i, j;
    if ((fp1 = fopen("D:\\C\\stud.txt", "rb")) == NULL){
        printf("open error!!");
        exit(0);
    }
    if ((fp2 = fopen("D:\\C\\stud_sort.txt", "wb")) == NULL){
        printf("write error!!\n");
        exit(0);
    }
    for (i = 0; i < 5; i++) {
        if (fread(&stud[i], sizeof(struct Student), 1, fp1) != 1) {
            printf("file read error\n");
            exit(0);
        }
    }
    for (i = 0; i < 5; i++) {
        for (j = i + 1; j < 5; j++) {
            if (stud[i].aver < stud[j].aver) {
                work = stud[i];
                stud[i] = stud[j];
                stud[j] = work;
            }
            fwrite(&stud[i], sizeof(struct Student), 1, fp2);
        }
    }
    fclose(fp1);
    fclose(fp2);
}
